package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;
import java.util.Stack;

/**
 * Title  : 530. Minimum Absolute Difference in BST
 * Source : https://leetcode.cn/problems/minimum-absolute-difference-in-bst/description/
 * Author : XrazYang
 * Date   : 2024-04-19
 */

public class LeetCode_530 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int getMinimumDifference(TreeNode root) {
        Stack<TreeNode> sta = new Stack<>();
        int min = Integer.MAX_VALUE, pre = -1;
        TreeNode cur = root;
        while (cur != null || !sta.isEmpty()) {
            if (cur != null) {
                sta.push(cur);
                cur = cur.left;
            } else {
                cur = sta.pop();
                if (pre != -1) {
                    min = Math.min(min, cur.val - pre);
                }
                pre = cur.val;
                cur = cur.right;
            }
        }
        return min;
    }
}
